<?php

/**
 * 前台通用控制器
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */

namespace app\common\controller;

class Front extends \think\Controller
{

    use \app\common\traits\Rpc;

    //强制登录
    protected $check_login = false;
    //商城分类
    protected $mall_cate = [];
    //会员ID
    protected $member_id = 0;
    //基本信息
    protected $member_info = [];
    //店铺ID
    protected $store_id = 0;
    //店铺信息
    protected $store_info = [];

    //初始化
    protected function _initialize()
    {
        //初始化站点配置
        $config = \Config::lists();
        $config['url_base'] = $this->request->domain() . "/";
        $config['mall_cate'] = \Fields::getById('goods_class');
        $config['article_cate'] = $this->articleCate();
        $config['module'] = $this->request->module();
        $config['controller'] = $this->request->controller();
        $config['action'] = $this->request->action();
        $config['page_tag'] = strtolower($config['module'] . "_" . $config['controller'] . "_" . $config['action']);
        config($config);
        $this->checkLogin($this->check_login);
        config('member_id', $this->member_id);
        config('member_info', $this->member_info);
        config('store_id', $this->store_id);
        config('store_info', $this->store_info);
    }

    /**
     * 验证登录
     */
    protected function checkLogin($must_login = false)
    {
        $this->member_info = cookie('uinfo');
        if ($this->member_info) {
            $this->member_id = session("uid");
        }
        if ($this->member_id > 0 && $this->member_info) {
            $this->member_info = unserialize($this->member_info);
            $this->store_id = session("sid");
            if ($this->store_id > 0) {
                $this->store_info = isset($this->member_info['store']) ? $this->member_info['store'] : [];
                if (!$this->store_info) {
                    $this->store_id = 0;
                }
            }
        } else {
            if ($must_login) {
                cookie('uinfo', null);
                $url = urlencode($this->request->url(true));
                $this->error('请先登录', '/?s=index/index/login&ref_url=' . $url);
            }
        }
    }

    /**
     * 文章分类
     * @return []
     */
    private function articleCate()
    {
        $cate = \Fields::get_tree_data("article", 1)['_child'];
        return reset_by_key($cate, 'tag');
    }

    /**
     * 获取数据
     * @param type $table
     * @param type $where
     * @param type $other
     * @param type $filter
     * @param type $para
     * @return type
     */
    protected function db_lists($table, $where = [], $other = [], $filter = '', $para = [])
    {
        if (is_string($other)) {
            $other = ['field' => $other];
        } else if (is_numeric($other)) {
            $other = ['limit' => $other];
        }

        $rs = rpc("common/common/lists", [$table, $where, $other]);
        if ($filter && is_string($filter) && function_exists($filter)) {
            $para = array_merge([$rs], is_array($para) ? $para : [$para]);
            return call_user_func_array($filter, $para);
        }
        return $rs;
    }

    /**
     * 获取数据 - 分页
     * @param type $table
     * @param type $where
     * @param type $limit
     * @param type $other
     * @param type $page_var
     * @param type $simple
     * @return type
     */
    protected function db_lists_page($table, $where = [], $limit = 10, $other = [], $page_var = 'curpage', $simple = false)
    {
        $page = $this->request->get($page_var, 1, 'intval');
        $rs = rpc("common/common/lists_page", [$table, $where, $page, $limit, $other]);
        $path = $this->request->baseUrl();
        if ($path == '/') {
            $path = $this->request->pathinfo();
        }
        $option = ['var_page' => $page_var, 'path' => $path, 'query'=>$this->request->param()];
        $rs = \Page::make($rs['data'], $rs['per_page'], $rs['current_page'], $rs['total'], $simple, $option);
        return $rs;
    }

    /**
     * 测试页面，不要引用
     * @param type $page
     * @return type
     */
    protected function test_html($page = '买家中心 - 一站式人力资源商城', $data = [])
    {
        return view("common@layout/test", ['name' => $page, 'data' => $data]);
    }

    /**
     * 上传通用操作
     * 
     * @param string $field 表单名
     * @param string $type  类型，可选 temp,logo,banner,image,album,goods,replace 
     *                       其中replace为替换模式，必须在$opt指定 original 参数，必须是 入口文件同级目录 下面的 路径文件
     * @param bool   $muti  是否批量上传
     * @param int    $opt   其它设置
     * 
     * @return []
     */
    protected function uploadFile($field = 'image', $type = 'image', $muti = false, $opt = [])
    {
        $root = ROOT_PATH . 'public/';
        $path = 'uploads/';

        $size = isset($opt['size']) ? $opt['size'] : 1 * 1024 * 1024;
        if ($type === 'replace') { //替换模式
            $original = $root . $opt['original'];
            if (!is_file($original)) { //要替换的文件不存在，直接返回false
                return [
                    'status' => false,
                    'total' => 0,
                    'error' => '要替换的文件不存在：' . $opt['original']
                ];
            }
            $save_path = dirname($original);
            $savename = basename($original);
            $ext = strtolower(pathinfo($savename, PATHINFO_EXTENSION));
            $muti = false;
        } else {
            $most = isset($opt['most']) ? $opt['most'] : 10;
            $ext = isset($opt['ext']) ? $opt['ext'] : 'jpg,png,gif,jpeg';
            $savename = isset($opt['savename']) ? $opt['savename'] : true;
            $type_allow = [
                'temp' => "temp/" . date('Y/m-d/'), //临时目录
                'joinin' => "joinin/".date('Y/m/'),
                'logo' => "logo/", //店铺logo
                'banner' => "banner/", //存储banner
                'brand' => "brand/", //品牌相关
                'album' => "album/" . $this->store_id . "/",
                'stamp' => 'stamp/' . date("Y/m-d/"),
                'waybill' => 'waybill/' . date("Y/m-d/"), //运单
                'goods' => "goods/" . date('Y/m-d/'), //商品图片
                'payment' => 'payment/' . date('Y/m-d/'), //支付凭证
                'image' => "images/" . date("Y/m-d/") //通用存储
            ];
            if (!$type || !isset($type_allow[$type])) {
                $type = 'image';
            }
            $save_path = $root . $path . $type_allow[$type];
        }

        //验证规则
        $validate = [
            'size' => $size, //最大1Ｍ
            'ext' => $ext    //允许上传的后缀
        ];

        $files = $this->request->file($field);
        if (!$muti && !is_array($files)) {
            $files = [$files];
        }

        $rs = [];
        $errorIndex = [];
        foreach ($files as $k => $file) {
            //防止非法数据
            if (!$file instanceof \think\File) {
                return [
                    'status' => false,
                    'total' => 0,
                    'error' => '数据异常'
                ];
            }
            // 移动到存储目录下
            $info = $file->rule('uniqid')->validate($validate)->move($save_path, $savename, true);

            if ($info) {
                if ($type === 'replace') { //替换模式
                    $rs[] = [
                        'status' => true,
                        'size' => $info->getInfo('size'),
                        'hash' => $info->hash(),
                        'original' => $info->getInfo('name')
                    ];
                } else {
                    $rs[] = [
                        'status' => true,
                        'ext' => $info->getExtension(), //后缀
                        'save_name' => str_replace("\\", "/", $info->getSaveName()), //存储名称
                        'save_path' => $this->request->root() . $path . $type_allow[$type],
                        'save_path_type' => $type_allow[$type],
                        'physical_path' => $save_path,
                        'file' => $info->getFilename(), //路径
                        'size' => $info->getInfo('size'), //大小
                        'type' => $info->getInfo('type'), //类型
                        'hash' => $info->hash(),
                        'original' => $info->getInfo('name') //原始文件名
                    ];
                }
            } else {
                $errorIndex[] = $k;
                $rs[] = [
                    "status" => false,
                    "error" => $file->getError()
                ];
            }

            if (!$muti) {
                //单个上传返回
                return $rs[0];
            }

            //超过上传个数，不再上传
            if (count($rs) >= $most) {
                break;
            }
        }

        //批量上传返回
        return [
            'status' => $errorIndex ? false : true,
            'total' => count($rs), //总共处理的图片
            'error_index' => $errorIndex, //上传失败的数组索引
            'error_num' => count($errorIndex), //失败个数
            'file' => $rs
        ];
    }

    public function _empty()
    {
        if ($this->request->isAjax()) {
            return callback(false, '模块功能暂未开放');
        } else {
            return '模块功能暂未开放，<a href="javascript:history.back(-1);">点击返回</a>';
        }
    }

    //时间查询
    protected function query_date()
    {
        $if_start_date = preg_match('/^\d{4}-\d{2}-\d{2}$/', input('query_start_date'));
        $if_end_date = preg_match('/^\d{4}-\d{2}-\d{2}$/', input('query_end_date'));
        $start_unixtime = $if_start_date ? strtotime(input('query_start_date')) : 0;
        $end_unixtime = $if_end_date ? strtotime(input('query_end_date')) : 0;
        $oneday = 3600 * 24 - 1;
        if ($start_unixtime > 0 && $end_unixtime > 0) {
            return ['between', [$start_unixtime, $end_unixtime + $oneday]];
        } else if ($start_unixtime > 0) {
            return ['between', [$start_unixtime, $start_unixtime + 10 * 365 * 3600 * 24]];
        } else if ($end_unixtime > 0) {
            return ['between', [0, $end_unixtime + $oneday]];
        }
        return false;
    }

}
